<?php

namespace MoChat\App\Sales\Action\AllocationTask;

use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Sales\Constants\SalesTaskStatusCode;
use MoChat\App\Sales\Contract\SalesTaskContract;
use MoChat\App\Sales\Contract\SalesTaskEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 销售任务列表
 * @Controller
 */
class Create extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var SalesTaskContract
     */
    protected $salesTaskService;

    /**
     * @Inject
     * @var SalesTaskEmployeeContract
     */
    protected $salesTaskEmployeeService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     * @RequestMapping(path="/dashboard/salesAllocationTask/create", methods="POST")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $this->validated($data);
        if (empty($data['userList']) || !count($data['userList'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '人员未选择');
        }
        Db::beginTransaction();
        try {
            $salesTask = $this->salesTaskService->getSalesTaskByIdLock($data['sales_task_id']);

            //获取已经分配了的任务总和
            $allocatedToTalTask = $salesTask['allocated_sales_task'];

            $surplus = bcsub($salesTask['salesTask'], $allocatedToTalTask, 2);
            if ($surplus <= 0) {
                throw new CommonException(ErrorCode::INVALID_PARAMS, '销量任务已分配完成');
            }

            $nowTask = bcmul(count($data['userList']), $data['sales_task'], 2);
            if ($nowTask > $surplus) {
                throw new CommonException(ErrorCode::INVALID_PARAMS, '当前分配总额' . $nowTask . '已超过剩余可分配销量' . $surplus);
            }

            //获取已经分配了员工
            $allocatedTasks = $this->salesTaskEmployeeService->getSalesTaskEmployeeBySalesTaskId($data['sales_task_id']);

            $arr = [];

            $updateArr = [];
            foreach ($data['userList'] as $item) {
                if (isset($allocatedTasks[$item])) {
                    $updateArr[] = [
                        'work_department_id' => $salesTask['workDepartmentId'],
                        'work_employee_id' => $item,
                        'sales_task' => $data['sales_task'],
                        'sales_task_id' => $data['sales_task_id'],
                        'start_time' => $data['start_time'],
                        'end_time' => $data['end_time'],
                        'title' => $data['title'],
                        'corp_id' => $user['corpIds'][0] ?? 0,
                        'remark' => $data['remark'] ?? '',
                    ];
                    continue;
                }
                $arr[] = [
                    'work_department_id' => $salesTask['workDepartmentId'],
                    'work_employee_id' => $item,
                    'sales_task' => $data['sales_task'],
                    'sales_task_id' => $data['sales_task_id'],
                    'start_time' => $data['start_time'],
                    'end_time' => $data['end_time'],
                    'corp_id' => $user['corpIds'][0] ?? 0,
                    'title' => $data['title'],
                    'remark' => $data['remark'] ?? '',
                ];
            }
            if (!empty($arr)) {
                $this->salesTaskEmployeeService->createSalesTaskEmployee($arr);
            }
            if (!empty($updateArr)) {
                foreach ($updateArr as $item) {
                    $number = $item['sales_task'];
                    unset($item['sales_task']);
                    $this->salesTaskEmployeeService->updateSalesTaskEmployee([
                        ['work_employee_id', '=', $item['work_employee_id']],
                        ['sales_task_id', '=', $item['sales_task_id']]
                    ], $number, $item);
                }
            }
            if (bccomp($nowTask, $surplus, 2) == 0) {
                $this->salesTaskService->updateSalesTaskById($data['sales_task_id'], [
                    'status' => SalesTaskStatusCode::ALLOCATION
                ]);
            }

            //更新已分配的指标
           $this->salesTaskService->updateAllocatedSalesTask($data['sales_task_id'], $nowTask);

            Db::commit();
        } catch (\Throwable $exception) {
            Db::rollBack();
        }
        return [];
    }

    /**
     * 验证规则.
     */
    protected function rules(): array
    {
        return [
            'sales_task' => 'required|numeric',
            'sales_task_id' => 'required|integer',
            'start_time' => 'required',
            'end_time' => 'required',
            'title' => 'max:30',
            'remark' => 'max:300',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    protected function messages(): array
    {
        return [
            'sales_task.required' => '单人任务量必填',
            'sales_task.numeric' => '单人任务量参数类型错误',
            'sales_task_id.required' => '销量任务id未选择',
            'sales_task_id.integer' => '销量任务id未类型错误',
            'start_time.required' => '开始时间不能为空',
            'end_time.required' => '结束时间不能为空',
            'title.max' => '任务标题长度不能超过30个字符',
            'remark.max' => '任务内容长度不能超过300个字符',
        ];
    }
}